#!/bin/bash
# usage: dlbrute [outdir]
# outdir is $tmp by default

jobs=15

base=${BASH_SOURCE[0]%/*}

site=http://mirror.archlinux.no

docs_official=$base/../lists/official

err() {
	echo >&2 "$*"
}

if [[ $EUID != 0 ]] ; then
	err 'run this as root.'
	exit 1
fi

tmp=$(mktemp -d /tmp/dlbrute.XXXXXXXX)

out=${1:-$tmp}

echo "TMP: $tmp"

pkg_info() {
	local pkg=$1
	local item=$2

	pacman "--config=$conffile" -Si "$pkg" |
	  awk -F: "/^$item/{ gsub(/^ /, \"\", \$2); print \$2 }" |
	  head -n1
}

for arch in i686 x86_64 ; do
	dbdir=$tmp/.pacman/$arch/db/
	logfile=$tmp/.pacman/$arch/pacman.log
	conffile=$tmp/.pacman/$arch/pacman.conf

	mkdir -p "$dbdir"
	mkdir -p "${logfile%/*}"
	mkdir -p "${conffile%/*}"

	cat > "$conffile" <<EOF
[options]
Architecture = $arch
SigLevel    = Never
#CacheDir    = $tmp/$arch
#DBPath      = $dbdir
#LogFile     = $logfile

[core]
Server = $site/\$repo/os/$arch

[extra]
Server = $site/\$repo/os/$arch

#[community]
#Server = $site/\$repo/os/$arch
EOF

	err 'syncing package database...'
	setarch $arch pacman "--config=$conffile" -Syy
	  #> /dev/null

	err "downloading package files to $out ..."
	cut -d' ' -f1 "$docs_official" |
	while read p ; do
		ver=$(pkg_info $p Version)
		pkg_arch=$(pkg_info $p Architecture)
		repo=$(pkg_info $p Repository)

		[[ $pkg_arch == any ]] || pkg_arch=$arch

		file=$p-$ver-$pkg_arch.pkg.tar.xz

		echo "$site/$repo/os/$arch/$file"{,.sig}
	done
done |
parallel --no-notice -n1 -j$jobs wget -P "$out" \
  > /dev/null 2>&1

echo "you may remove $tmp now"

rm -f "$tmp/get_helper.sh"
